<?php

namespace app\admin\controller;

use app\admin\model\UserCourse;
use app\common\controller\Backend;
use app\admin\model\User;
use think\Db;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("fromList", $this->model->getFromList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['venue','course','user','admin'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
                    //->fetchSql(true)->select();
            foreach ($list as &$row) {
                $row->term = DB::name('user_course')->where('order_no',$row->order_no)->where('status',0)->find();
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $user = $this->auth->getUserInfo();
        if ($user['venue_id'] !=0) {
            $this->assignconfig("vid", $user['venue_id']);
        }
        return $this->view->fetch();
    }

    /*
     * 团体课预订
     * */
    public function plan($ids = null) {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $term = Db::name('term')->where('id',$params['term_id'])->find();
            $user = explode(',',$params['user_ids']);
            $count = count($user);

            if ($count < $term['num']) {
                $this->error(__('该学期需要'.$term['num'].'人，请继续选择'));
            }
            if ($count > $term['num']) {
                $this->error(__('该学期限制人数'.$term['num'].'人，请删减'));
            }
            //$userCourse = DB::name('user_course')->where('order_no',$row->order_no)->where('status',0)->select()->toArray();

            Db::startTrans();
            try {
                UserCourse::where('order_no',$row->order_no)->update(['status' => 1]);
                foreach ($user as $v) {
                    UserCourse::insert([
                        'order_no' => $row->order_no,
                        'venue_id' => $row->venue_id,
                        'user_id' => $v,
                        'term_id' => $params['term_id'],
                        'coach_id' => $term['user_id'],
                        'course_id' => $row->course_id,
                        'ctime' => time(),
                        'time' => time(),
                        'type' => 1,
                    ]);
                }

                Db::commit();
               // return $this->redirect('course_push/add');

              // return $this->success('编辑成功','order/index', true);
                $this->success();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function changePlan($ids = null) {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Db::startTrans();
        try {
            UserCourse::where('order_no',$row->order_no)->update(['status' => 1]);
            Db::commit();
            //$this->redirect('/order/index');
            $this->success();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        $user = $this->auth->getUserInfo();
        if ($user['venue_id'] !=0) {
            $this->view->assign("vid", $user['venue_id']);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($params['phone']) {
                    $phone = Db::name('user')->where('mobile', $params['phone'])->find();
                    if (!$phone) {
                        $this->error('未查到该用户');
                    }
                }
                if ($user['venue_id'] !=0) {
                    $params['venue_id'] = $user['venue_id'];
                }
                //dump($params);die;


                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //创建新订单
                    do{
                        $order_no = create_order_code();
                        $orderInfo = DB::name('order')->where('order_no','=',$order_no)->find();
                    }while(!empty($orderInfo));
                    $data = [
                        'order_no' => $order_no,
                        'venue_id' => $params['venue_id'],
                        'user_id' => $phone['id'],
                        'snapshot' => "充值金额-".$params['price']."元",
                        'ctime' => time(),
                        'ptime' => time(),
                        'price' => $params['price'],
                        'pay_type' => $params['pay_type'],
                        'type' => 1,
                        'proof_images' => $params['proof_images'],
                        'from' => 1,
                        'admin_id' => $user['id'],
                        'remarks' => $params['remarks'],
                        'status' => 1
                    ];
                    DB::name('order')->insert($data);
                    //修改用户账户金额
                    $orderInfo = DB::name('order')->where('order_no','=',$order_no)->find();
                    $newMoney = bcadd($phone['money'], $orderInfo['price'], 2);
                    $data = [
                        'user_id' => $phone['id'],
                        'money' => $orderInfo['price'],
                        'before' => $phone['money'],
                        'after' => $newMoney,
                        'memo' => '金额储值',
                        'order_no' => $order_no,
                        'createtime' => time()
                    ];
                    DB::name('user_money_log')->insert($data);
                    DB::name('user')->where('id',$phone['id'])->update(['money' => $newMoney]);

                   // $result = $this->model->allowField(true)->save($params);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    public function del($ids = "")
    {
        try {
            Db::startTrans();
            DB::name('order')->where('id', '=', $ids)->update( ['status' => 3] );
            $orderInfo = DB::name('order')->where('id', '=', $ids)->find();
            $user =  User::where('id', $orderInfo['user_id'])->find();
            $money = bcsub( $user['money'],  $orderInfo['price'], 2  );

            $param = [
                'user_id' => $user['id'],
                'money' => $orderInfo['price'],
                'before' => $user['money'],
                'after' => $money,
                'memo' => '取消储值',
                'order_no' => $orderInfo['order_no'],
                'createtime' => time()
            ];
            DB::name('user_money_log')->insert($param);
            User::where('id', $user['id'] )->update( ['money' => $money] );
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('删除成功');
    }

}
